import wx from 'weixin-js-sdk'
import sha1 from 'crypto-js/sha1'
import qs from 'qs';
import Toast from 'components/Toast';
import { isWechat } from 'libs/tools';

const defaultShareImg = 'http://file.jzdoctor.com/vaccine-zone/share.png';
const defaultLink = `https://${DEPLOY_ENV === 'prod' ? 'app' : 'testapp'}.jzdoctor.com/vaccine-zone?fromWhere=wechat-share`;
const defaultTitle = '彩虹育儿';
const defaultDescription = '你想打的疫苗信息都在这里';

const firstPageUrl = window.location.href;

if (location.href.includes('useFirst=true')) {
	localStorage.setItem('useFirstUrl', 'true');
}

if (location.href.includes('useFirst=false')) {
	localStorage.setItem('useFirstUrl', 'false');
}

function getPageUrl() {
	let useFirstUrl = localStorage.useFirstUrl;
	let url;

	if (useFirstUrl) {
		if (useFirstUrl === 'true') {
			url = firstPageUrl;
		}
		else {
			url = window.location.href;
		}
		console.log(`真实url:`, '\n', window.location.href, `sign用url:`, '\n', url, '\n');
	}
	else {
		var isiOS = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);
		url = isiOS ? firstPageUrl : window.location.href;
	}
	return url;
}

function onBridgeReady(){
	WeixinJSBridge.call('showOptionMenu');
	WeixinJSBridge.call('hideToolbar');
}

if (typeof WeixinJSBridge == "undefined"){
	if( document.addEventListener ){
		document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
	}else if (document.attachEvent){
		document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
		document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
	}
}else{
	onBridgeReady();
}



const wxjssdk = {
	init (props) {
		let timestamp = (new Date().getTime()+'').substr(0,10)
		let nonceStr = sha1(timestamp).toString()
		let appid = APP_CONFIG.appId
		let ticket = ''
		var xhr = new XMLHttpRequest()
		if (process.env.NODE_ENV !== 'development') {
			xhr.withCredentials = true
		}
		let url = APP_CONFIG.wechat + '/js/ticket.json'
		xhr.open('GET', url, false)
		xhr.onreadystatechange = function () {
			if (xhr.readyState === 4 && (xhr.status === 200)) {
				let resp = JSON.parse(xhr.responseText)
				if (resp.statusCode === 0) {
					ticket = resp.data.ticket
				} else {
					// console.log('token xhr in 200: ', JSON.stringify(xhr));
					if(isWechat()){
						oauth();
					}
				}
			}
			else {
				// console.log('token xhr not in 200: ', JSON.stringify(xhr));
			}
		}
		xhr.send(null)
		// }

		let signStr = 'jsapi_ticket=' + ticket + '&noncestr=' + nonceStr + '&timestamp=' + timestamp + '&url=' + getPageUrl();
		console.log('signStr-=-=',signStr)
		let signature = sha1(signStr).toString()
		wx.config({
			debug: qs.parse(window.location.href.split('?')[1]).wechatDebug,
			// 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
			appId: appid, // 必填，公众号的唯一标识
			timestamp: timestamp, // 必填，生成签名的时间戳
			nonceStr: nonceStr, // 必填，生成签名的随机串
			signature: signature, // 必填，签名，见附录1
			jsApiList: [
				'onMenuShareTimeline',
				'onMenuShareAppMessage',
				'onMenuShareQQ',
				'onMenuShareWeibo',
				'onMenuShareQZone',
				'updateAppMessageShareData',
				'updateTimelineShareData',
				'startRecord',
				'stopRecord',
				'onVoiceRecordEnd',
				'playVoice',
				'pauseVoice',
				'stopVoice',
				'onVoicePlayEnd',
				'uploadVoice',
				'downloadVoice',
				'chooseImage',
				'previewImage',
				'uploadImage',
				'downloadImage',
				'translateVoice',
				'getNetworkType',
				'openLocation',
				'getLocation',
				'hideOptionMenu',
				'showOptionMenu',
				'hideMenuItems',
				'showMenuItems',
				'hideAllNonBaseMenuItem',
				'showAllNonBaseMenuItem',
				'closeWindow',
				'scanQRCode',
				'chooseWXPay',
				'openProductSpecificView',
				'addCard',
				'chooseCard',
				'openCard'
			] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
		})
		wx.ready(function () {
		})
		wx.error(function (res) {
			// config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
			console.log('初始化微信JS-SDK失败', res);
			throw res;
		})
	},
	initDefaultShare: function () {
	},
	chooseImage: function (callback) {
		wx.chooseImage({
			count: 4, // 默认9
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
			success: function (res) {
				// 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
				callback(res.localIds)
			}
		})
	},
	uploadImage: function (localId, callback) {
		let serverId = ''
		wx.uploadImage({
			localId: localId, // 需要上传的图片的本地ID，由chooseImage接口获得
			isShowProgressTips: 1, // 默认为1，显示进度提示
			success: function (res) {
				serverId = res.serverId // 返回图片的服务器端ID
				callback(serverId)
			}
		})
	},
	previewImg: function (url, urls) {
		wx.previewImage({
			current: url,
			urls: urls
		})
	},
	saveImage: function () {
		wx.saveImageToPhotosAlbum({
			success (res) {
				alert(JSON.stringify(res))
			}
		})
	},
	initShare: function (linkUrl, title, des, imgUrl, from_origin, cid) {

		let shareConfig = {
			title: title|| '彩虹育儿', // 分享标题
			link: linkUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
			imgUrl: imgUrl , // 分享图标
			success: function () {
				// Toast({text:'分享成功'})
			},
			cancel: function () {
				Toast({text:'分享失败'})
			}
		};


		wx.onMenuShareTimeline(shareConfig)

		// 分享给朋友
		wx.onMenuShareAppMessage({
			...shareConfig,
			desc: des || defaultDescription, // 分享描述
		})

		//  // 新分享朋友接口
		// wx.updateAppMessageShareData({
		//   ...shareConfig,
		//   desc: des || defaultDescription, // 分享描述
		// });
		//
		//  // 新分享到朋友圈
		// wx.updateTimelineShareData(shareConfig);
	},
	wx: wx
};
const getAccessToken =() =>{
	let ak = window.localStorage.getItem('access_token')
	return ak
};


const payPost = (URL, PARAMS) => {
	var form = document.createElement('form')
	form.action = URL
	form.method = 'get'
	form.style.display = 'none'
	for (var x in PARAMS) {
		let hidden = document.createElement('input')
		hidden.setAttribute('type', 'hidden')
		hidden.setAttribute('name', x)
		hidden.setAttribute('value', PARAMS[x])
		form.appendChild(hidden)
	}
	document.body.appendChild(form)
	form.submit()
};
/**
 * 认证方法
 * @param props
 * @param ve 当前vue对象
 */
export const oauth = ()  =>{
	let URL = APP_CONFIG.wechatOauth;
	let DATA = {
		redirect_url: encodeURIComponent(window.location.href),
		appid: APP_CONFIG.appId,
		cookie: true
	}
	payPost(URL, DATA)
};

// oauth();
export default wxjssdk;

window.wxjssdk = wxjssdk;


